<template>
  <view class="verification-page">
    <!-- 顶部扫码核销按钮 -->
    <view class="scan-section">
      <button class="scan-button" @click="scanToVerify">
        <uni-icons type="scan" size="24" color="#fff"></uni-icons>
        <text class="scan-text">扫码核销</text>
      </button>
    </view>

    <!-- 核销记录列表 -->
    <view class="record-section">
      <view class="section-title">核销记录</view>
      <scroll-view scroll-y class="record-list">
        <view 
          class="record-item" 
          v-for="record in verificationRecords" 
          :key="record.id"
          @click="goToVerificationDetail(record)"
        >
          <view class="record-header">
            <text class="record-id">核销单号：{{ record.verificationId }}</text>
            <text class="record-status" :class="getStatusClass(record.status)">
              {{ record.statusText }}
            </text>
          </view>
          <view class="record-content">
            <view class="product-info">
              <text class="product-name">{{ record.productName }}</text>
              <text class="verification-time">核销时间：{{ record.verificationTime }}</text>
            </view>
            <view class="record-price">
              <text class="price">¥{{ record.totalPrice }}</text>
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="verificationRecords.length === 0">
          <uni-icons type="circle" size="40" color="#ccc"></uni-icons>
          <text class="empty-text">暂无核销记录</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getOrderRedemptionLogPage } from '@/services/order.js';

// 核销记录数据
const verificationRecords = ref([]);

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 'completed':
      return 'status-completed';
    default:
      return '';
  }
};

// 获取核销记录数据
const fetchVerificationRecords = async () => {
  try {
    console.log('开始调用 getOrderRedemptionLogPage 接口');
    const params = {
      pageNum: 1,
      pageSize: 20
    };
    console.log('请求参数:', params);
    
    const response = await getOrderRedemptionLogPage(params);
    console.log('getOrderRedemptionLogPage 接口返回:', response);
    
    // 根据实际返回的数据结构调整这里
    // 先检查响应结构，尝试多种可能的数据结构
    if (response) {
      let records = [];
      
      // 尝试不同的数据结构路径
      if (response.records) {
        records = response.records;
      } else if (response.data && response.data.records) {
        records = response.data.records;
      } else if (response.pageData && response.pageData.records) {
        records = response.pageData.records;
      } else if (Array.isArray(response)) {
        records = response;
      } else if (response.data && Array.isArray(response.data)) {
        records = response.data;
      } else if (response.pageData && Array.isArray(response.pageData)) {
        records = response.pageData;
      }
      
      console.log('解析后的记录:', records);
      verificationRecords.value = records.map(record => ({
        id: record.id || record.orderNo || Date.now() + Math.random(),
        verificationId: record.orderNo || record.id || '',
        orderId: record.orderNo || '',
        status: record.status || 'completed',
        statusText: record.statusText || record.statusDesc || '已核销',
        productName: record.productName || record.name || record.title || '乒乓球桌预约',
        verificationTime: record.createTime || record.verificationTime || record.operateTime || new Date().toLocaleString('zh-CN', { 
          year: 'numeric', 
          month: '2-digit', 
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        }).replace(/\//g, '-'),
        price: record.refundAmount || record.amount || record.totalPrice || record.price || 0,
        totalPrice: record.refundAmount || record.amount || record.totalPrice || record.price || 0
      }));
    } else {
      // 如果没有数据，保持空数组
      verificationRecords.value = [];
    }
    
    console.log('最终verificationRecords数据:', verificationRecords.value);
  } catch (error) {
    console.error('获取核销记录失败:', error);
    // 显示更详细的错误信息
    let errorMsg = '获取核销记录失败';
    if (error.message) {
      errorMsg = error.message;
    } else if (error.errMsg) {
      errorMsg = error.errMsg;
    }
    
    uni.showToast({
      title: errorMsg,
      icon: 'none',
      duration: 3000
    });
    // 出错时也清空列表
    verificationRecords.value = [];
  }
};

// 扫码核销
const scanToVerify = () => {
  // 模拟扫码功能
  uni.scanCode({
    success: (res) => {
      console.log('扫码成功', res);
      uni.showToast({
        title: '核销成功',
        icon: 'success'
      });
      
      // 生成核销记录
      const newRecord = {
        id: Date.now(), // 使用时间戳作为唯一ID
        verificationId: 'VF' + new Date().getTime(),
        status: 'completed',
        statusText: '已核销',
        productName: '乒乓球桌预约',
        verificationTime: new Date().toLocaleString('zh-CN', { 
          year: 'numeric', 
          month: '2-digit', 
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        }).replace(/\//g, '-'),
        price: 60
      };
      
      verificationRecords.value.unshift(newRecord);
      
      // 保存核销记录到本地存储
      try {
        uni.setStorageSync('verificationRecords', verificationRecords.value);
      } catch (error) {
        console.error('保存核销记录失败:', error);
      }
    },
    fail: (err) => {
      console.log('扫码失败', err);
      uni.showToast({
        title: '扫码失败',
        icon: 'none'
      });
    }
  });
};

// 跳转到核销详情页面
const goToVerificationDetail = (record) => {
  // 传递订单ID到核销详情页面
  uni.navigateTo({
    url: `/pages/list/verificationDetail?orderId=${record.orderId}`
  });
};

// 页面加载时初始化
const initPage = () => {
  console.log('核销列表页面加载');
  fetchVerificationRecords();
};

// 只在页面加载时初始化一次
onLoad(() => {
  initPage();
});
</script>

<style lang="scss" scoped>
.verification-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
}

.scan-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx;
  margin-bottom: 20rpx;
  text-align: center;
  
  .scan-button {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #3b82f6;
    color: #fff;
    border: none;
    border-radius: 50rpx;
    padding: 24rpx 60rpx;
    font-size: 32rpx;
    
    .scan-text {
      margin-left: 16rpx;
    }
  }
}

.record-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
}

.record-list {
  height: calc(100vh - 300rpx);
}

.record-item {
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  
  .record-id {
    font-size: 28rpx;
    color: #333;
  }
  
  .record-status {
    font-size: 24rpx;
    padding: 4rpx 12rpx;
    border-radius: 4rpx;
    
    &.status-completed {
      background-color: #e8fff0;
      color: #2ab363;
    }
  }
}

.record-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-info {
  .product-name {
    font-size: 30rpx;
    color: #333;
    display: block;
    margin-bottom: 10rpx;
  }
  
  .verification-time {
    font-size: 24rpx;
    color: #999;
  }
}

.record-price {
  .price {
    font-size: 32rpx;
    color: #e60012;
    font-weight: bold;
  }
}

.empty-state {
  text-align: center;
  padding: 80rpx 0;
  
  .empty-text {
    display: block;
    font-size: 28rpx;
    color: #999;
    margin-top: 20rpx;
  }
}
</style>